package com.juzipi.demo.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.juzipi.demo.pojo.Role;
import com.juzipi.demo.pojo.User;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public final class JwtUtil {

    public static final String SUBJECT = "大家晚上好啊！";
    public static final String SALT = "I‘ve been a closed book full of mistakes";
    public static final long EXPIRE = 1000 * 24 * 60 * 60 * 7;//7天

    public static String getToken(User user){
        //看不懂，大概就是转类型？
        String roles = Optional.ofNullable(user.getRoleList())
                .orElse(new ArrayList<>()).stream()
                .map(Role::getRoleName)
                .collect(Collectors.joining(","));
        String token = JWT.create()
                .withSubject(SUBJECT)
                .withClaim("id", user.getId())
                .withClaim("username", user.getUsername())
                .withClaim("roles", roles)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE))//过期时间
                .sign(Algorithm.HMAC256(SALT));
        return token;
    }


    public static boolean verify(String token){
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SALT)).withSubject(SUBJECT).build().verify(token);
        } catch (Exception e) {
            throw new JWTDecodeException("token验证失败");
        }
        System.out.println("========================================> token验证完毕");
        return true;
    }


    public static User getAuthentication(String token) {
        DecodedJWT decode = JWT.decode(token);
        String username = decode.getClaim("username").asString();
        if (StringUtils.isNotBlank(username)){
            User user = User.getInstance();
            user.setUsername(username);
            user.setId(decode.getClaim("id").asLong());
            String roles = decode.getClaim("roles").asString();
            if (StringUtils.isNotBlank(roles)){
                //这个真的看不懂了
                List<Role> roleList = Stream.of(roles.split(",")).filter(StringUtils::isNotBlank).map(v -> {
                    Role role = Role.getInstance();
                    role.setRoleName(v);
                    return role;
                }).collect(Collectors.toList());
                user.setRoleList(roleList);
            }
            return user;
        }
        return null;
    }

}
